package org.truenewx.tnxjeex.unit.repo.jpa.converter;

import jakarta.persistence.AttributeConverter;

import org.truenewx.tnxjee.core.util.ClassUtil;
import org.truenewx.tnxjeex.unit.model.MeasureUnit;
import org.truenewx.tnxjeex.unit.support.MeasureUnits;

public abstract class AbstractMeasureUnitAttributeConverter<T extends MeasureUnit<?>>
        implements AttributeConverter<T, String> {

    @Override
    public String convertToDatabaseColumn(T attribute) {
        return attribute == null ? null : attribute.getValue();
    }

    @Override
    public T convertToEntityAttribute(String dbData) {
        return MeasureUnits.getInstance().fromValue(getUnitClass(), dbData);
    }

    protected Class<T> getUnitClass() {
        return ClassUtil.getActualGenericType(getClass(), 0);
    }

}
